<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="产品" prop="productId">
        <el-input
          v-model="queryParams.productId"
          placeholder="请输入产品"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="米数" prop="meters">
        <el-input
          v-model="queryParams.meters"
          placeholder="请输入米数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="入库时间" prop="enterTime">
        <el-date-picker clearable
          v-model="queryParams.enterTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择入库时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="审核状态" prop="enterStatus">
        <el-select v-model="queryParams.enterStatus" placeholder="请选择入库审核状态" clearable>
          <el-option
            v-for="dict in dict.type.zc_store_enter"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sales:storeEnter:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['sales:storeEnter:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['sales:storeEnter:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['sales:storeEnter:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="storeEnterList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="入库单id" align="center" prop="enterId" /> -->
      <el-table-column label="产品" align="center" prop="productId" width="280">
        <template slot-scope="scope">{{getProductName(scope.row.productId)}}</template>
      </el-table-column>
      <el-table-column label="米数" align="center" prop="meters" />
      
      <el-table-column label="入库人" align="center" prop="staffId" >
        <template slot-scope="scope">
          <span>{{ getStaffName(scope.row.staffId) }}</span> 
        </template>
      </el-table-column>
      <el-table-column label="入库时间" align="center" prop="enterTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.enterTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="入库审核状态" align="center" prop="enterStatus">
        <template slot-scope="scope">
          <el-tag :type="scope.row.enterStatus === 0 ? 'warning' : (scope.row.enterStatus === 1 ? 'success' : 'danger')"> 
            <dict-tag :options="dict.type.zc_store_enter" :value="scope.row.enterStatus"/>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
          v-show="scope.row.enterStatus === 0"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['sales:storeEnter:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sales:storeEnter:remove']"
          >删除</el-button>
          <el-button
          v-show="scope.row.enterStatus === 0"
            size="mini"
            type="text"
            icon="el-icon-finished"
            @click="handleCheck(scope.row)"
          >审核</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改入库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="产品" prop="productId">
          <!-- filterable 可搜索 -->
          <el-select v-model="form.productId" placeholder="请选择要入库的产品" filterable>
              <el-option
                v-for="item in productsOptions"
                :key="item.productId"
                :label="item.name"
                :value="item.productId"
              />
            </el-select>
        </el-form-item>
        <el-form-item label="米数" prop="meters">
            <el-input v-model="form.meters" placeholder="请输入米数" type="number" />
          </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog :title="title" :visible.sync="statusOpen" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="产品" prop="productId">
          <!-- filterable 可搜索 -->
          <el-select v-model="form.productId" placeholder="请选择要入库的产品" disabled>
              <el-option
                v-for="item in productsOptions"
                :key="item.productId"
                :label="item.name"
                :value="item.productId"
              />
            </el-select>
        </el-form-item>
        <el-form-item label="审核状态" prop="enterStatus">
          <template>
            <el-radio v-model="form.enterStatus" label="1">通过</el-radio>
            <el-radio v-model="form.enterStatus" label="2">驳回</el-radio>
          </template>
        </el-form-item>
        <el-form-item label="成品仓库" prop="storeId">
          <el-select v-model="form.storeId" placeholder="请选择成品仓库" filterable>
            <el-option
              v-for="item in okStoreOptions"
              :key="item.storeId"
              :label="item.storeName"
              :value="item.storeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <!-- 文本域高度可通过 rows 属性控制 -->
            <el-input v-model="form.remark" placeholder="请输入备注" type="textarea"/>
          </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormCheck">确 定</el-button>
        <el-button @click="cancelCheck">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStoreEnter, getStoreEnter, delStoreEnter, addStoreEnter, updateStoreEnter, changeCheckStatus, okStoreListSelect } from "@/api/sales/storeEnter";
import { productsListSelect } from "@/api/sales/data";

export default {
  name: "StoreEnter",
  dicts: ['zc_store_enter'],
  data() {
    var validateMeters = (rule, value, callback) => {  
      // 正则表达式，匹配正整数  
      const regex = /^\d+$/;
      if (!regex.test(value)) {  
        callback(new Error('请输入有效的正整数米数'));  
      } else if (value <= 0) {  
        callback(new Error('米数必须为正整数'));  
      } else {  
        callback();  
      } 
    }; 
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入库表格数据
      storeEnterList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      statusOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productId: null,
        storeId: null,
        meters: null,
        enterTime: null,
        enterStatus: null,
        remark: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productId: [
          { required: true, message: "产品不能为空", trigger: "blur" }
        ],
        meters: [
            { required: true, validator: validateMeters, trigger: "blur" }
        ],
        remark:[
          { required: true, message: "备注不能为空", trigger: "blur" }
        ],
        enterStatus:[
          { required: true, message: "审核状态不能为空", trigger: "blur" }
        ]
      },
      //产品选项
      productsOptions: undefined,
      //成品仓库选项
      okStoreOptions: undefined,
    };
  },
  created() {
    this.getList();
    this.getProductsList();
    this.getOkStoreList();
  },
  methods: {
    // 查询成品仓库列表
    getOkStoreList(){
      okStoreListSelect().then((response) => {
        this.okStoreOptions = response.data;
      })
    },
    getProductName(productId){
            // 遍历 productsOptions 数组以找到匹配的 productNumber  
            const foundItem = this.productsOptions.find(item => item.productId === productId);  
            // 如果找到了匹配的项，返回其 productName，否则返回空字符串或未定义  
            return foundItem ? foundItem.name : '';
        },
    getStaffName(staffId){
      // 遍历 storeEnterList 数组以找到匹配的 staffId  
      const foundItem = this.storeEnterList.find(item => item.staffId === staffId);  
      // 如果找到了匹配的项，返回其 staffName，否则返回空字符串或未定义  
      return foundItem ? foundItem.staffName : ''; 
    },
    /** 查询产品列表 */
    getProductsList(){
      productsListSelect().then((response) => {
        this.productsOptions = response.data;
      })
    },
    /** 查询入库列表 */
    getList() {
      this.loading = true;
      listStoreEnter(this.queryParams).then(response => {
        this.storeEnterList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancelCheck(){
      this.statusOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        enterId: null,
        virtuallyId: null,
        productId: null,
        storeId: null,
        meters: null,
        staffId: null,
        enterTime: null,
        enterStatus: 0,
        remark: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        del: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.enterId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加入库单据";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const enterId = row.enterId || this.ids
      getStoreEnter(enterId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改入库单据";
      });
    },
    /** 审核按钮操作 */
    handleCheck(row){
      this.reset();
      getStoreEnter(row.enterId).then(response => {
        this.form = response.data;
        this.statusOpen = true;
        this.title = "办事处审核";
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.enterId != null) {
            updateStoreEnter(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStoreEnter(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    submitFormCheck(){
      this.$refs["form"].validate(valid => {
        if (valid && this.form.enterId != null) {
          changeCheckStatus(this.form).then(response => {
            // if(response.data.enterStatus == 0){
            //   this.$modal.msgSuccess("未审核，请注意");
            //   this.statusOpen = false;
            // this.getList();
            // }else if(response.data.enterStatus == 1){
            //   this.$modal.msgSuccess("审核通过");
            //   this.statusOpen = false;
            // this.getList();
            // }else{
              
            // }
            this.$modal.msgSuccess("审核成功");
              this.statusOpen = false;
            this.getList();
            });
            
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const enterIds = row.enterId || this.ids;
      this.$modal.confirm('是否确认删除入库单据编号为"' + enterIds + '"的数据项？').then(function() {
        return delStoreEnter(enterIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    
    /** 导出按钮操作 */
    handleExport() {
      this.download('sales/storeEnter/export', {
        ...this.queryParams
      }, `storeEnter_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
